<?php
include_once $_SERVER['DOCUMENT_ROOT']."/controller/connect.php";
include_once $_SERVER['DOCUMENT_ROOT']."/model/Application.php";
/**
 * Created by PhpStorm.
 * User: lwh
 * Date: 2017/7/22
 * Time: 19:35
 */
class ApplicationDAO{
    const FIELD_ID = "applicationId";
    const FIELD_USER_ID = "userId";
    const FIELD_STAGE_ID = "stageId";

    public $conn;

    function __construct()
    {
        $this->conn = new db();
    }

    //插入
    public function insert($application){
        $db = $this->conn->getDBConn();
        $stmt = $db->prepare("insert into application(userId,stageId) values(?,?)");
        $stmt->bindParam(1,$application[self::FIELD_USER_ID],PDO::PARAM_INT);
        $stmt->bindParam(2,$application[self::FIELD_STAGE_ID],PDO::PARAM_INT);
        $result = $stmt->execute();
        return $result;
    }

    //删除
    public function delete($applicationId){

    }

    //查询
    public function query($applicationId){
        $sql = "select * from application where ".self::FIELD_ID." = ".$applicationId;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if($row){
            $application = $this->loadDataFromResult($row);
            return $application;
        }
        else
            return null;
    }

    //更新
    public function update($application){

    }

    //通过用户id和stageid查询
    public function queryByUserAndStage($userId,$stageId){
        $sql = "select * from application where ".self::FIELD_USER_ID." = ".$userId." and ".self::FIELD_STAGE_ID." = ".$stageId;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if($row){
            $application = $this->loadDataFromResult($row);
            return $application;
        }
        else
            return null;
    }

    //根据用户id和stageid删除
    public function deleteByUserAndStage($userId,$stageId){
        $sql = "delete from application where ".self::FIELD_USER_ID." = ".$userId." and ".self::FIELD_STAGE_ID." = ".$stageId;
        $db = $this->conn->getDBConn();
        $result = $db->exec($sql);
        return $result;
    }

    //从结果集中构建出application对象
    private function loadDataFromResult($row){
        $application = new Application();
        $application->setId($row[self::FIELD_ID]);
        $application->setUserId($row[self::FIELD_USER_ID]);
        $application->setStageId($row[self::FIELD_STAGE_ID]);
        return $application;
    }

}
